package de.haw.ai3.bs.aufgabe3.a2;

import java.security.SecureRandom;
import java.util.HashSet;

import de.haw.ai3.bs.aufgabe3.a2.table.Table;


public class Agent extends Thread {
	
	private HashSet<Zutat> verfuegbar;
	private Table table; 
	
	private final SecureRandom randomizer = new SecureRandom();
	
	public Agent(HashSet<Zutat> verfuegbareZutaten, Table table){
		this.verfuegbar = verfuegbareZutaten;
		this.table = table;
	}

	@Override
	public void run() {
		while (!isInterrupted()) {
			try {
				table.platzieren(waehleZutaten(), this);
			} catch (InterruptedException e) {
				interrupt();
			}
		}
	}

	private Zutat[] waehleZutaten() {
		HashSet<Zutat> zutaten = new HashSet<>();
		while (zutaten.size() < table.CAPACITY) {
			zutaten.add(getRandomZutat());
		}
		return zutaten.toArray(new Zutat[zutaten.size()]);
	}

	private Zutat getRandomZutat() {
		return verfuegbar.toArray(new Zutat[verfuegbar.size()])[getIndex()];
	}
	
	public int getIndex() {
		return randomizer.nextInt(table.CAPACITY - 0 + 1) + 0;
	}

	@Override
	public String toString() {
		return "Agent";
	}

}
